package com.flowerplus.store.common.data.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.support.v4.content.SharedPreferencesCompat;

import com.flowerplus.store.App;
import com.flowerplus.store.common.structure.key.TokenKey;

import javax.inject.Inject;

/**
 * Created by z on.
 * Des:SharedPreferences工具类
 * Date: 2017/3/6
 */

public class SpUtil {
    Context mContext;
    private final SharedPreferences mSharedPreferences;
    private static SpUtil sSpUtil = new SpUtil(App.getApp().getApplicationContext());

    public static SpUtil getInstance() {
        return sSpUtil;
    }

    @Inject
    public SpUtil(Context context) {
        this.mContext = context.getApplicationContext();
        mSharedPreferences = mContext.getSharedPreferences("app", Context.MODE_PRIVATE);
    }

    public SpUtil() {
        this.mContext = App.getApp().getApplicationContext();
        mSharedPreferences = mContext.getSharedPreferences("app", Context.MODE_PRIVATE);
    }

    public void putString(String key, String value) {
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        editor.putString(key, value);
        apply(editor);
    }

    public String getString(String key) {
        return getString(key, null);
    }

    public String getString(String key, String defaultStr) {
        return mSharedPreferences.getString(key, defaultStr);
    }

    public void putBoolean(String key, boolean value) {
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        editor.putBoolean(key, value);
        apply(editor);
    }

    public void clear() {
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        editor.remove(TokenKey.IP).apply();
        editor.remove(TokenKey.USER_ID);
        editor.remove(TokenKey.TOKEN);
        apply(editor);
    }

    public boolean getBoolean(String key) {
        return mSharedPreferences.getBoolean(key, false);
    }

    public boolean getBoolean(String key, boolean def) {
        return mSharedPreferences.getBoolean(key, def);
    }

    public void putInt(String key, int value) {
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        editor.putInt(key, value);
        apply(editor);
    }

    public void putLong(String key, long value) {
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        editor.putLong(key, value);
        apply(editor);
    }

    public long getLong(String key) {
        return mSharedPreferences.getLong(key, -1);
    }

    public int getInt(String key) {
        return mSharedPreferences.getInt(key, -1);
    }

    public void apply(SharedPreferences.Editor editor) {
        SharedPreferencesCompat.EditorCompat.getInstance().apply(editor);
    }
}
